import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/home/Home.vue'
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/Login.vue'),
    beforeEnter: (to, from, next) => {
      const isLogin = localStorage.getItem('isLogin')
      if (isLogin) {
        next({ name: 'Home' })
      } else {
        next()
      }
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/register/Register.vue')
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    // 懒加载
    component: () => import('../views/shop/Shop.vue')
  },
  {
    path: '/cartList',
    name: 'CartList',
    component: () => import('../views/cartList/CartList.vue')
  },
  {
    path: '/order/:id',
    name: 'Order',
    component: () => import('../views/order/Order.vue')
  },
  {
    path: '/orderList',
    name: 'OrderList',
    component: () => import('../views/orderList/OrderList.vue')
  }
]
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
// 每次路由跳转都会执行一次
router.beforeEach((to, from, next) => {
  const isLogin = localStorage.isLogin
  const LoginorRegister = to.name === 'Login' || to.name === 'Register'
  if (isLogin || LoginorRegister) {
    next()
  } else {
    next({ name: 'Login' })
  }
})

export default router
